package com.qingluan.dd;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;


import com.qingluan.Database.Personal_Info_database;
import com.qingluan.arguments.ARGUMENTS;
import com.qingluan.dd.InetTool.Sign_up;
import com.qingluan.dd.InetTool.Sign_up.FailedCall;
import com.qingluan.dd.InetTool.Sign_up.Sign_up_Callback;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SignUpActivity extends Activity {
	private final static  String SIGN_UP_URL = ARGUMENTS.ROOT_URL + "register";
	private EditText sign_phone,sign_pass , sign_email,sign_name;
	private Button sign_button;
	private Sign_up Sign_up_client;
	private Button turn ;
	private Context context_this_activity;
	private ProgressDialog progerDialog;
	//finger arguments area
	private int startX;
	private boolean IS_RECORDED = false;
	
	//sign up argu area
	private String token_id;
	private String token_key;
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        
        context_this_activity = getApplicationContext();
        
        sign_phone = (EditText)findViewById(R.id.sign_phone);
        sign_pass = (EditText)findViewById(R.id.sign_password);
        sign_email = (EditText)findViewById(R.id.sign_email);
        sign_name = (EditText)findViewById(R.id.sign_name);
        sign_button = (Button) findViewById(R.id.sign_button);
        /*
        turn = (Button) findViewById(R.id.sign_button);
        turn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(SignUpActivity.this,LoginActivity.class);
				SignUpActivity.this.startActivity(intent);
			}
        	
        });
        */
        sign_button.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				progerDialog = ProgressDialog.show(SignUpActivity.this, "Sign up ", "completing..",true,false);
				HashMap<String,String>argv = null ;
				argv = CommitCheck();
				if (argv != null){
					Log.d("My_argv","i get :" +argv.toString());
					final String phone = argv.get("phone");
					final String pass =argv.get("pass");
					final String email = argv.get("email");
					final String name = argv.get("name");
					JSONObject sign_info = new JSONObject();
					try {
						sign_info.put("name", name);
						sign_info.put("email", email);
						sign_info.put("password",pass);
						sign_info.put("phone", phone);
						
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					Sign_up_client =  new Sign_up(SIGN_UP_URL);
					Log.d("I_GET","json : "+sign_info.toString());
					Sign_up_client.pushArgument("JSON_SIGN", sign_info.toString());
					Sign_up_client.post(new Sign_up_Callback(){
						
						@Override
						public void callback(String json) {
							progerDialog.dismiss();
							// TODO Auto-generated method stub
							JSONObject ResponseObject = null;
							String response = null;
							Log.d("I_GET","服务器你妹的"+json);
							
							try {
								ResponseObject =new JSONObject(json);
								Log.d("I_GET","get from net sign :"+json);
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							
							try {
								if(ResponseObject != null){
									Log.d("I_GET","T_T 好感动啊，注册成功了");
									response = ResponseObject.getString("response");
									token_id = ResponseObject.getString("user_id");
									token_key = ResponseObject.getString("user_key");
								}else {
									Log.d("I_GET","Error   ..." + response);
								}
							} catch (JSONException e) {
								Toast.makeText(context_this_activity, email.toString(), Toast.LENGTH_SHORT).show();
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							/*
							 * check if sign-up-task is right
							 */
							if (response.equals("ok")){
								Log.d("I_GET","sign up successful !");
								Toast.makeText(getApplicationContext(), "Sign up successful!", Toast.LENGTH_SHORT).show();
								
								Personal_Info_database DB = new Personal_Info_database(context_this_activity);
								ContentValues people_values = new ContentValues();
								people_values.put("uid", phone);
								people_values.put("name", name);
								people_values.put("email", email);
								people_values.put("password", pass);
								people_values.put("describe", "null");
								people_values.put("picture_url", "null");
								
								if (
										DB.searchEmail(phone) != null 
										&&
										!DB.searchEmail(phone).equals(email)){
									DB.insertMyTag(people_values);
								}
								
								Intent intent = new Intent(SignUpActivity.this,LoginActivity.class);
								SignUpActivity.this.startActivity(intent);
							}else if (response.equals("fail")){
								Log.d("I_GET","sign up failed ");
								Toast.makeText(context_this_activity, "This account exist!!", Toast.LENGTH_SHORT).show();
							}
						
						}
						
					},new FailedCall(){

						@Override
						public void callback(String msg) {
							progerDialog.dismiss();
							// TODO Auto-generated method stub
							Toast.makeText(getApplicationContext(), "error"+msg, Toast.LENGTH_SHORT).show();

						}

						
					});

				}
			}
			
        });
        
        
    }

    public HashMap<String,String> CommitCheck(){
    	String name = sign_name.getText().toString();
    	String phone = sign_phone.getText().toString();
    	String pass = sign_pass.getText().toString();
    	String email = sign_email.getText().toString();
    	
    	if ( PhoneCheck(phone)){
    		if ( PassCheck(pass)){
    			if (EmailOrPhoneCheck(email)){
    				HashMap<String,String>argv = new HashMap<String,String>();
    	    		argv.put("phone", phone);
    	    		argv.put("pass", pass);
    	    		argv.put("email", email);
    	    		argv.put("name", name);
    	    		return argv;
    			}
    		}
    	}
    		
    	
    	return null;
    }
    public boolean NameCheck(String name){
    	if (name.length()<= 1){
    		sign_name.setFocusable(true);
    		sign_name.requestFocus();
    		Toast.makeText(getApplicationContext(), "You should type a name ,not blank", Toast.LENGTH_SHORT).show();
    		return false;
    	}
    	return true;
    }
    public boolean PhoneCheck(String number){
    	if (number.length() < 11){
    		sign_phone.setFocusable(true);
    		sign_phone.requestFocus();
    		Toast.makeText(getApplicationContext(), "you should type a right phone ", Toast.LENGTH_SHORT).show();
    		return false;
    	}
    	return true;
    }
    public boolean EmailOrPhoneCheck(String number){
    	if (number.length() <2 ){
    		sign_email.setFocusable(true);
    		sign_email.requestFocus();
    		Toast.makeText(getApplicationContext(),"you shoudle type a right value "
    				, Toast.LENGTH_SHORT).show();
    		return false;
    	}
    	
    	return true ;
    }
    public boolean PassCheck(String pass){
    	if (pass.length() < 5){
    		Toast.makeText(getApplicationContext(),"pass length should > 5 ,You get : "
    				+ String.valueOf(pass.length()), Toast.LENGTH_SHORT).show();
    		sign_pass.setFocusable(true);
    		sign_pass.requestFocus();
    		return false;
    	}
    	return true;
    }
    @Override
    public boolean onTouchEvent(MotionEvent ev){
    	int tempX = (int) ev.getX();
    	if (IS_RECORDED == false){
    		startX = tempX;
    		this.IS_RECORDED = true;
    	}
    	if (tempX - startX >200){
    		Intent intent = new Intent(SignUpActivity.this,LoginActivity.class);
    		SignUpActivity.this.startActivity(intent);
    	}
    	return false;
    }
    
    @Override
    public void onBackPressed(){
    	Intent intent = new Intent(SignUpActivity.this,LoginActivity.class);
    	SignUpActivity.this.startActivity(intent);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.sign_up, menu);
        return true;
    }
    
}
